/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sun.scheduler.util.graph.algorithm.maxflow;

import java.util.Iterator;
import sun.scheduler.util.graph.Edge;
import sun.scheduler.util.graph.Node;

/**
 *
 * @author mfj
 */
public class EdmondKarpAlgorithm implements MaxFlowAlgorithm
{

    private ResidualGraph rGraph;
    private int sourceId;
    private int targetId;

    public EdmondKarpAlgorithm(ResidualGraph rGraph, int sourceId, int targetId)
    {
        if (sourceId == targetId)
            throw new IllegalArgumentException("Source and Target are identical.");

        this.rGraph = rGraph;
        this.sourceId = sourceId;
        this.targetId = targetId;
    }

    @Override
    public ResidualGraph getResidualGraph()
    {
        return rGraph;
    }

    @Override
    public Node getSource()
    {
        return rGraph.getGraph().getNode(sourceId);
    }

    @Override
    public Node getTarget()
    {
        return rGraph.getGraph().getNode(targetId);
    }

    @Override
    public double getFlow()
    {
        int f = 0;
        Node gSource = getSource();
        Iterator iter = gSource.edgeIterator();
        while (iter.hasNext())
        {
            Edge<Label, EdgeFlow> next = (Edge<Label, EdgeFlow>) iter.next();
            f += next.getData().getFlow();

        }
        return f;
    }

    @Override
    public void run()
    {
        while (rGraph.augmentPath(sourceId, targetId))
        {
        }
    }

}
